package main

import (
	"errors"
	"fyne.io/fyne"
	"fyne.io/fyne/app"
	"fyne.io/fyne/dialog"
	"fyne.io/fyne/layout"
	"fyne.io/fyne/theme"
	"fyne.io/fyne/widget"
	"github.com/PuerkitoBio/goquery"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"ipscan/util"
	"net/http"
)

const versionNow = "1.0.0"

func initLog() {
	glog.SetPath("./logs/")
	glog.SetStdoutPrint(false)
	//glog.Info("欢迎使用hosts加速服务")

	/*
		中文显示
		e := gproc.ShellRun("set FYNE_FONT=C:\\Windows\\Fonts\\consola.ttf")
		glog.Info("设置环境变量:", e)
	*/

}

//todo:返回参数放到defer里也不会返回异常时候赋值的信息
func updateCheck() (returnbool bool, returnstring string) {
	returnbool = false
	returnstring = ""
	defer func() {
		if err := recover(); err != nil {
			glog.Error("检测版本失败:", err)
			returnstring = "检测版本失败"
		}
	}()
	api := "https://gitee.com/dwxdfhx/SpeedUpNet/blob/master/version.txt"
	version := ""
	res, err := http.Get(api)
	if err != nil {
		returnstring = "检测版本失败"
		panic("检测版本失败")
	} else {
		defer res.Body.Close()
		if res.StatusCode != 200 {
			returnstring = "检测版本失败"
			panic("检测版本失败")
		} else {
			doc, err := goquery.NewDocumentFromReader(res.Body)
			if err != nil {
				returnstring = "检测版本失败"
				panic("检测版本失败")
			}
			version = doc.Find(".line").First().Text()
			version = gstr.Replace(version, "\n", "")
		}
	}

	versionArrayCheck := gstr.Split(version, ".")
	versionArrayNow := gstr.Split(versionNow, ".")
	nowversion := gconv.Int(versionArrayNow[0])*100 + gconv.Int(versionArrayNow[1])*10 + gconv.Int(versionArrayNow[2])
	checkversion := gconv.Int(versionArrayCheck[0])*100 + gconv.Int(versionArrayCheck[1])*10 + gconv.Int(versionArrayCheck[2])
	if checkversion > nowversion {
		glog.Info("检测到新版本发布!")
		returnbool = true
		returnstring = "检测到新版本发布,版本:V" + version
	} else {
		returnbool = false
		returnstring = "未检测到新版本"
	}
	return returnbool, returnstring
}

/**
 */
func main() {
	initLog()
	update, updateinfo := updateCheck()

	canQuit := true

	a := app.NewWithID("io.dw.speedupnet")
	a.SetIcon(theme.FyneLogo())
	a.Settings().SetTheme(theme.LightTheme())

	w := a.NewWindow("域名最快hosts映射")
	w.Resize(fyne.Size{Width: 650, Height: -1})

	w.SetFixedSize(true)
	w.CenterOnScreen()

	domainWidget := widget.NewEntry()
	domainWidget.SetPlaceHolder("github.com")
	quitWidget := widget.NewButton("Quit", func() {
		if canQuit {
			a.Quit()
		} else {
			dialog.ShowError(errors.New("Update In Progress..."), w)
			return
		}
	})
	updateButton := widget.NewButton("", nil)
	updateButton.Hide()
	if update {
		updateButton.Show()
		updateButton.SetText(updateinfo)
		updateButton.OnTapped = func() {
			util.OpenUrl("https://gitee.com/dwxdfhx/SpeedUpNet/tree/master/build")
		}
	}

	w.SetContent(widget.NewVBox(
		widget.NewLabelWithStyle("Welcome to SpeedUp Net!", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}),
		widget.NewLabel("domain:"),
		domainWidget,
		widget.NewLabel(""),
		quitWidget,
		widget.NewButton("Run", func() {
			if !canQuit {
				dialog.ShowError(errors.New("Update In Progress..."), w)
				return
			}
			canQuit = false
			quitWidget.Disable()

			domainTemp := domainWidget.Text
			ip, err := util.GetIp(domainTemp)
			if err == nil {
				util.UpdateHOST(domainTemp, ip)
				dialog.ShowInformation("success ", "domain:"+domainTemp+" update hosts success!", w)
				canQuit = true
				quitWidget.Enable()
			} else {
				glog.Error("GetIp error:", err)
				dialog.ShowError(errors.New("update hosts fail!"), w)
				canQuit = true
				quitWidget.Enable()
			}
		}),
		widget.NewButton("View hosts", func() {
			hosts := util.ReadHosts()
			w := fyne.CurrentApp().NewWindow("本地hosts查看")
			w.SetContent(fyne.NewContainerWithLayout(layout.NewCenterLayout(), widget.NewLabel("Hello World!")))
			w.CenterOnScreen()
			w.Resize(fyne.NewSize(1024, 768))

			path := util.GetPath()
			pathTitle := widget.NewLabel("Path:")
			//无效
			//pathTitle.Resize(fyne.NewSize(20, 300))
			pathV := widget.NewEntry()
			pathV.SetText(path)
			pathV.Resize(fyne.Size{Width: 1024, Height: 20})
			pathComp := fyne.NewContainerWithLayout(layout.NewBorderLayout(nil, nil, pathTitle, nil), pathTitle, pathV)

			c1 := widget.NewMultiLineEntry()
			c1.SetText(hosts)
			c1.Resize(fyne.NewSize(1024, 760))
			c1scrol := widget.NewScrollContainer(c1)
			c1scrol.Resize(fyne.NewSize(1024, 760))

			c3 := fyne.NewContainerWithLayout(layout.NewBorderLayout(pathComp, nil, nil, nil),
				pathComp, c1scrol)
			c3.Resize(fyne.NewSize(1024, 760))

			w.SetContent(c3)
			w.Show()
		}),
		updateButton,
	))
	w.ShowAndRun()

}
